/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package projeto;

import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import projeto.classes.ModeloUsuario;
import projeto.classes.UsuarioAcessaDados;


/**
 *
 * @author admin
 */
public class Usuario extends javax.swing.JInternalFrame {

    
    ModeloUsuario usr;
    UsuarioAcessaDados usrDao;
    ArrayList<ModeloUsuario> lista;
    
    /**
     * Creates new form UsuarioFrame
     */
    public Usuario() {
        initComponents();
        btnAlterar.setEnabled(false);
        btnExcluir.setEnabled(false);
        txtNome.setEnabled(false);
        txtCpf.setEnabled(false);
        txtSenha.setEnabled(false);
        cmbAtivo.setEnabled(false);
        cmbAdmUser.setEnabled(false);
        cmbPesquisa.setEnabled(false);
        
        usr = new ModeloUsuario();
        usrDao = new UsuarioAcessaDados();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtConsulta = new javax.swing.JTextField();
        btnConsultar = new javax.swing.JToggleButton();
        jLabel7 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtNome = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        lblCodigo = new javax.swing.JLabel();
        txtCpf = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        txtSenha = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        cmbAtivo = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        cmbAdmUser = new javax.swing.JComboBox();
        btnNovo = new javax.swing.JButton();
        btnAlterar = new javax.swing.JButton();
        btnSair = new javax.swing.JButton();
        btnExcluir = new javax.swing.JButton();
        cmbPesquisa = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        cmbOpcaoPesquisa = new javax.swing.JComboBox();

        setTitle("Entrega Gado - Usuário");

        btnConsultar.setText("Consultar");
        btnConsultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConsultarActionPerformed(evt);
            }
        });

        jLabel7.setText("Consultar por:");

        jLabel3.setText("Nome:");

        jLabel9.setText("Código:");

        lblCodigo.setText("--");

        jLabel4.setText("CPF:");

        jLabel8.setText("Senha:");

        jLabel5.setText("Ativo");

        cmbAtivo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Não", "Sim" }));

        jLabel6.setText("Super usuário");

        cmbAdmUser.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Não", "Sim" }));

        btnNovo.setText("Novo");
        btnNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNovoActionPerformed(evt);
            }
        });

        btnAlterar.setText("Alterar");
        btnAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAlterarActionPerformed(evt);
            }
        });

        btnSair.setText("Sair");
        btnSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSairActionPerformed(evt);
            }
        });

        btnExcluir.setText("Excluir");
        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });

        cmbPesquisa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbPesquisaActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel2.setText("USUÁRIO");

        cmbOpcaoPesquisa.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Nome", "CPF" }));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(53, 53, 53)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel7)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4)
                            .addComponent(jLabel8)
                            .addComponent(jLabel5))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(cmbAtivo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(cmbAdmUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(txtCpf, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, 290, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel9)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(77, 77, 77)
                                        .addComponent(cmbPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(cmbOpcaoPesquisa, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(txtConsulta, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnConsultar))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(211, 211, 211)
                        .addComponent(jLabel2))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(65, 65, 65)
                        .addComponent(btnNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(67, 67, 67)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(74, 74, 74)
                                .addComponent(btnSair, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(46, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addGap(25, 25, 25)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(txtConsulta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnConsultar)
                    .addComponent(cmbOpcaoPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cmbPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9)
                    .addComponent(lblCodigo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtCpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(txtSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbAtivo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6)
                    .addComponent(cmbAdmUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(91, 91, 91)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnNovo)
                    .addComponent(btnAlterar)
                    .addComponent(btnSair))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
                .addComponent(btnExcluir)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConsultarActionPerformed
        if (txtConsulta.getText().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Informe o nome do usuário para consulta", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
        } else {
            //seta o ArrayList para null
            lista = null;
            String filtro = "";
            if (cmbOpcaoPesquisa.getSelectedIndex() == 0) {
                //pesquisa por nome
                filtro = "nm_usuario LIKE '" + txtConsulta.getText() + "%'";  
            }
            
            if (cmbOpcaoPesquisa.getSelectedIndex() == 1) {
                //pesquisa por cpf
                filtro = "cd_cpf_usuario = '" + txtConsulta.getText() + "'"; 
            }

            try {
                lista = usrDao.consulta(filtro);

                if (lista.isEmpty()) {
                    JOptionPane.showMessageDialog(this, "Não foram localizados usuarios com a informação: " + txtConsulta.getText(), "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
                }

                if (lista.size() > 0) {
                    if (cmbPesquisa.getItemCount() > 0) {
                        cmbPesquisa.removeAllItems();
                    }
                    cmbPesquisa.setEnabled(true);
                    btnAlterar.setEnabled(true);
                    btnExcluir.setEnabled(true);
                    txtNome.setEnabled(false);
                    txtCpf.setEnabled(false);
                    txtSenha.setEnabled(false);
                    cmbAtivo.setEnabled(false);
                    cmbAdmUser.setEnabled(false);
                    btnNovo.setText("Novo");

                    //seleciona o 1º (ou o unico) item da lista
                    ModeloUsuario modeloTd = lista.get(0);
                    cmbPesquisa.addItem(modeloTd.getNome());
                    cmbPesquisa.setSelectedIndex(0);
                    cmbPesquisaActionPerformed(evt);
                }

                if (lista.size() > 1) {
                    //apenas inclui os outros componentes na lista (se houver)
                    for (int i = 1; i <= lista.size() - 1; i++) {
                        ModeloUsuario modeloTd = lista.get(i);
                        cmbPesquisa.addItem(modeloTd.getNome());
                    }
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "Erro ao consultar " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_btnConsultarActionPerformed

    private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed
        if (btnNovo.getText().equals("Novo")) {
            txtNome.setEnabled(true);
            txtNome.setText("");
            txtCpf.setEnabled(true);
            txtCpf.setText("");
            txtSenha.setEnabled(true);
            txtSenha.setText("");
            lblCodigo.setText("--");
            cmbAtivo.setEnabled(true);
            cmbAdmUser.setEnabled(true);
            btnNovo.setText("Salvar");
            btnAlterar.setEnabled(false);
            btnExcluir.setEnabled(false);
        } else {
            //clicou no salvar
            if (txtSenha.getText().isEmpty() || txtNome.getText().isEmpty() || txtCpf.getText().isEmpty()) {
                JOptionPane.showMessageDialog(this, "Nome, CPF e senha são obrigatórios", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
            } else {
                usr.setNome(txtNome.getText());
                usr.setCpf(txtCpf.getText());
                usr.setSenha(txtSenha.getText());
                usr.setAtivo(cmbAtivo.getSelectedIndex());
                usr.setUsuarioAdmin(cmbAdmUser.getSelectedIndex());

                try {
                    if (!usrDao.incluir(usr)) {
                        JOptionPane.showMessageDialog(this, "Dados gravados", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
                        btnNovo.setText("Novo");
                        btnAlterar.setEnabled(true);
                        btnExcluir.setEnabled(true);
                        int maxId = usrDao.consultaMaxId();
                        lblCodigo.setText(maxId + "");
                        txtNome.setEnabled(false);
                        txtCpf.setEnabled(false);
                        txtSenha.setEnabled(false);
                        cmbAtivo.setEnabled(false);
                        cmbAdmUser.setEnabled(false);
                    }

                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(this, "Erro ao gravar " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
                }

            }

        }
    }//GEN-LAST:event_btnNovoActionPerformed

    private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed
        if (btnAlterar.getText().equals("Alterar")) {
            txtNome.setEnabled(true);
            txtCpf.setEnabled(true);
            txtSenha.setEnabled(true);
            cmbAtivo.setEnabled(true);
            cmbAdmUser.setEnabled(true);
            btnAlterar.setText("Salvar");
            btnExcluir.setEnabled(false);
        } else {
            if (txtSenha.getText().isEmpty() || txtNome.getText().isEmpty() || txtCpf.getText().isEmpty()) {
                JOptionPane.showMessageDialog(this, "Nome, CPF e senha são obrigatórios", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
            } else {
                usr.setId(Integer.parseInt(lblCodigo.getText()));
                usr.setNome(txtNome.getText());
                usr.setCpf((txtCpf.getText().isEmpty()) ? "" : txtCpf.getText());
                usr.setSenha(txtSenha.getText());
                usr.setAtivo(cmbAtivo.getSelectedIndex());
                usr.setUsuarioAdmin(cmbAdmUser.getSelectedIndex());

                try {
                    if (usrDao.alterar(usr) > 0) {
                        JOptionPane.showMessageDialog(this, "Dados alterados", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
                        btnAlterar.setText("Alterar");
                        txtNome.setEnabled(false);
                        txtCpf.setEnabled(false);
                        txtSenha.setEnabled(false);
                        cmbAtivo.setEnabled(false);
                        cmbAdmUser.setEnabled(false);
                        btnExcluir.setEnabled(false);
                    }

                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(this, "Erro ao gravar " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }//GEN-LAST:event_btnAlterarActionPerformed

    private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnSairActionPerformed

    private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
        if (txtSenha.getText().isEmpty() || txtNome.getText().isEmpty() || txtCpf.getText().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Nome, CPF e senha são obrigatórios", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
        } else {
            try {
                int id = Integer.parseInt(lblCodigo.getText());

                if (usrDao.deletar(id) == 1) {
                    JOptionPane.showMessageDialog(this, "Registro excluido", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
                    txtNome.setText("");
                    txtCpf.setText("");
                    txtSenha.setText("");
                    cmbAtivo.setSelectedIndex(0);
                    cmbAdmUser.setSelectedIndex(0);
                    btnExcluir.setEnabled(false);
                    btnAlterar.setEnabled(false);
                }

            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "Erro ao excluir " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
            }
        }

    }//GEN-LAST:event_btnExcluirActionPerformed

    private void cmbPesquisaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbPesquisaActionPerformed
        if (evt.getSource().getClass().getSimpleName().equals("JComboBox")) {
            JComboBox cmb = (JComboBox)evt.getSource();
            int index = cmb.getSelectedIndex();
            if (index != -1) {
                ModeloUsuario modeloTd = lista.get(index);
                String id = modeloTd.getId() + "";
                String nome = modeloTd.getNome();
                String cpf = modeloTd.getCpf();
                int ativo = modeloTd.getAtivo();
                int adm = modeloTd.getUsuarioAdmin();
                String senha = modeloTd.getSenha();
                lblCodigo.setText(id);
                txtNome.setText(nome);
                txtCpf.setText(cpf);
                txtSenha.setText(senha);
                cmbAtivo.setSelectedIndex(ativo);
                cmbAdmUser.setSelectedIndex(adm);
            }
        }
    }//GEN-LAST:event_cmbPesquisaActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAlterar;
    private javax.swing.JToggleButton btnConsultar;
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnNovo;
    private javax.swing.JButton btnSair;
    private javax.swing.JComboBox cmbAdmUser;
    private javax.swing.JComboBox cmbAtivo;
    private javax.swing.JComboBox cmbOpcaoPesquisa;
    private javax.swing.JComboBox cmbPesquisa;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JLabel lblCodigo;
    private javax.swing.JTextField txtConsulta;
    private javax.swing.JTextField txtCpf;
    private javax.swing.JTextField txtNome;
    private javax.swing.JTextField txtSenha;
    // End of variables declaration//GEN-END:variables
}
